package fr.norsys.mapper.console.model;

import fr.norsys.mapper.console.utils.UIDGenerator;
import java.util.TreeMap;
import java.util.Map;
import java.util.Collection;
import java.util.Iterator;
import java.util.ArrayList;

public class IntFilter extends BaseObject {
	private static final long serialVersionUID = 7619304349682780639L;
	private String id;
	private String operator;
	private String value;
	private Map filterList;
	
	public IntFilter() {
		super();
		this.id = UIDGenerator.generateId();
		this.operator = "ET";
		this.value = "";
		this.filterList = new TreeMap();
	}

	public void save(Filter f){
		this.filterList.put(f.getId(),f);
		maj();
	}
	
	public void delete(String id){
		this.filterList.remove(id);
		maj();
	}
	/**
	 * Change the operator value
	 * @param op
	 * @return
	 */
	public void changeOp(String op){
		this.setOperator(op);
		maj();
	}
	
	public Filter get(String id){
		return (Filter) this.filterList.get(id);
	}
	/**
	 * Update the filter value  
	 * @return
	 */
	private void maj(){
		Filter f = new Filter();
		Collection c = this.filterList.values();
		Iterator i = c.iterator();
		if(nbAttr()>1){
			if (this.operator.equals("OU")){
				this.value = "(|";
			} else if (this.operator.equals("ET")){
				this.value = "(&";
			} 
		} else {this.value = "";}
		
		while(i.hasNext()){
			f = (Filter) i.next();
			this.value+="(";
			if (f.getNon()){this.value += "!(";}
			if (f.getIdent()){
				this.value += f.getAttribute()+"=${"+f.getValue()+"})";
			}
			else {
				this.value += f.getAttribute()+"="+f.getValue()+")";
			}
			if (f.getNon()){this.value += ")";}
		}
		if(nbAttr()> 1 && !this.operator.equals("")){
			this.value += ")";
		}
	}
	/**
	 * Return the number of elements int the filter list  
	 * @return int
	 */
	public int nbAttr(){
		return filterList.size();
	}
	
	public ArrayList getFilterList(){
		Collection c = this.filterList.values();
		ArrayList tab = new ArrayList(c);
		return tab;
	}
	
	public void setFilterList(Map m){
		this.filterList = (TreeMap) m;
	}

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}

	public String getOperator() {
		return operator;
	}
	public void setOperator(String operator) {
		this.operator = operator;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
		
}